<template>
    <div class="subpage">
        <My-head title="忘记密码">
            <van-icon name="revoke" color="#f50" class="hicon"/>
        </My-head>

        <van-form @submit="onSubmit" @failed="onFail">
            <!-- 手机号 -->
            <van-field
            autocomplete="off"
            v-model="form.phone"
            name="phone"
            label="手机号"
            placeholder="请输入手机号"
            left-icon="phone-o"
            clearable
            :rules="[
                { required: true, message: '请输入手机号' },
                { pattern: reg.phone, message: '请输入正确的手机号' }
            ]"
            />

            <!-- 验证码  使用value值 必须绑定name="captcha" 否则响应失败-->
            <van-field
            v-model="form.captcha"
            name="captcha"
            center
            clearable
            left-icon="qr"
            label="验证码"
            placeholder="请输入验证码"
            :rules="[
                { required: true, message: '请输入验证码' },
                { pattern: reg.code, message: '验证码错误' } // 该验证码为4为数字组成
            ]"
            >
            <template #button>
                <!-- 有手机号才能发送验证码，否则验证码不能点击发送 -->
                <van-button v-if="flag" size="small" :disabled="disabled" type="primary" @click.stop.prevent="sendCaptcha">发送验证码</van-button>
                <van-button v-else size="small" disabled  > {{count}} S</van-button>
            </template>
            </van-field>

            <!-- 新密码 -->
            <van-field
                autocomplete="off"
                v-model="form.password"
                :type="type"
                name="password"
                label="新密码"
                left-icon="shield-o"
                :right-icon="type == 'password' ? 'closed-eye' : 'eye-o'"
                @click-right-icon="changeType"
                placeholder="请输入新密码"
                clearable
                :rules="[
                { required: true, message: '请输入新密码' },
                { validator: checkpass, message: '请输入6-16位数字+字母组合密码' }
                ]"
            />

            <div style="margin: 16px;display:flex;" class="jcsb"  >
                <p>
                    <router-link :to="{name:'register'}" class="link1 mb10">还未注册,去注册?</router-link>
                </p>
                <p>
                    <router-link :to="{ name: 'login' }" class="link1 mb10">已有账号,去登录?</router-link>
                </p>
            </div>

            <div style="margin: 16px;">
                <van-button  block type="primary" native-type="submit">确认修改</van-button>
            </div>

        </van-form>
    </div>
</template>

<script>

var timer = null

export default {
  data() {
    return {
      form: {},
      type: 'password',
      flag: true,
      count: 60
    }
  },
  mounted() {
    this.form  = {
      phone: this.$route.query.phone ? this.$route.query.phone : localStorage.getItem('phone')
    }
  },
  computed: {
    disabled() {
      return !this.reg.phone.test(this.form.phone)
    }
  },
  destroyed() { // 离开销毁计数器
    clearInterval(timer)
    timer = null
  },
  methods: {
    checkpass(val){
      return this.reg.pwd.test(val)
    },
    async send() {
      let res = await this.$ajax.sendCaptcha({
        phone: this.form.phone 
      })
      const { code } = res
      if(code == 200){
        this.showSuccessMsg("验证码发送成功!")
      } else {
        this.showErrorMsg("验证码发送失败,今日次数已经用完!")
      }
    },
    sendCaptcha() { // 获取验证码
    this.send()

    this.flag =false
    this.count--
    timer = setInterval(() => {
      if(this.count > 0){
        this.count--
        this.flag = false
      } else {
        clearInterval(timer)
        timer = null
        this.count = 60
        this.flag = true 
      }
    }, 1000)
  },
    onSubmit(value) {
      console.log(value)
      // 先判断手机号是否已经被注册
      // 被注册才能校验 
      // 没有注册提示用户去注册

      this.$ajax.findUser({
        phone: value.phone,
      })
      .then(result => {
        console.log(result)

        if(result.length > 0){
          this.$ajax.verifyCaptcha({
            phone: value.phone,
            captcha: value.captcha
          })
          .then(res => {
             const { code } = res
             if(code == 200){
              //  修改密码
              if(value.password == result[0].password) {
                this.showErrorMsg('新密码不能跟旧密码一样.')
              } else {
                this.$ajax.updatePassword(result[0].id, {
                  password: value.password,
                })
                .then(res => {
                  this.showSuccessMsg("密码修改成功")
                  this.$nextTick(() => {
                    this.$router.push({ name: 'login' })
                  })
                })
              }

             } else {
               this.showErrorMsg("校验失败,请重新验证")
             }
          })
        } else {
          this.showErrorMsg("该手机号未被注册,请先注册")
        }
      })
    },
    onFail(){
      this.$toast.fail('请输入有效的修改信息')
    },
    changeType() {
      this.type = this.type == 'password' ? 'type' : 'password'
    },
  }
}
</script>

<style lang="scss" scoped>


</style>